<template>
	<div class="app-container">
		<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
			<!-- <el-tab-pane v-for="tab in allowedTabs" :label="tab.label" :name="tab.name" :key="tab.name"></el-tab-pane> -->
			<el-tab-pane label="我的数据" name="0"></el-tab-pane>
			<el-tab-pane label="全部数据" name="5" v-if="hasRole(['admin', 'BOSS', 'DEPT_LEADER'])"></el-tab-pane>
			<el-tab-pane label="领导审批" name="2" v-if="hasRole(['BOSS'])"></el-tab-pane>
			<el-tab-pane label="部门审批" name="1" v-else-if="hasRole(['DEPT_LEADER'])"></el-tab-pane>
		</el-tabs>

		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
			label-width="68px">

			<el-form-item label="报销编号" prop="businessCode">
				<el-input v-model="queryParams.businessCode" placeholder="请输入编号" clearable
					@keyup.enter.native="handleQuery" />
			</el-form-item>

			<el-form-item label="用户名称" prop="uid">
				<el-select v-model="queryParams.uid" filterable placeholder="请选择用户">
					<el-option v-for="item in userData" :key="item.userId" :label="item.nickName" :value="item.userId">
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="部门" prop="deptId" v-if="activeName == 5">
				<treeselect style="width: 215px;" v-model="queryParams.deptId" :options="deptOptions" :show-count="true"
					placeholder="请选择部门" />
			</el-form-item>

			<el-form-item label="时间" prop="timeData">
				<el-date-picker v-model="timeData" type="daterange" range-separator="至" start-placeholder="开始日期"
					end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="timeChange">
				</el-date-picker>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8" v-if="activeName == 0">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
					v-hasPermi="['business:bxExpense:add']">新增
				</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
					@click="handleDelete" v-hasPermi="['business:bxExpense:remove']">删除
				</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<!-- 报销管理表格 -->
		<el-table v-loading="loading" :data="bxExpenseList" @selection-change="handleSelectionChange">
			<!-- 选择列 -->
			<el-table-column type="selection" width="55" align="center" />
			<!-- 其他列 -->
			<el-table-column label="编号" align="center" prop="businessCode" width="200" />
			<el-table-column label="报销概述" align="center" prop="title" width="330" show-overflow-tooltip />
			<el-table-column sortable label="报销时间" align="center" prop="businessDate" width="180">
				<!-- 时间格式化 -->
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="用户名称" align="center" prop="nickName" />
			<el-table-column label="单据数量" align="center" prop="dtlCnt" />
			<el-table-column sortable label="报销总额" align="center" prop="totalPrice" />
			<el-table-column label="状态" align="center" prop="status">
				<!-- 报销状态标签 -->
				<template slot-scope="scope">
					<el-tag type="danger" v-if="scope.row.status == 0">待提交</el-tag>
					<el-tag type="warning" v-if="scope.row.status == 1">部门审核中</el-tag>
					<el-tag v-if="scope.row.status == 2">领导审核中</el-tag>
					<el-tag type="success" v-if="scope.row.status == 9">完成</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<!-- 操作按钮 -->
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
						v-hasPermi="['business:bxExpense:edit']" v-if="scope.row.status == 0 && activeName == 0">
						修改
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)"
						v-hasPermi="['business:bxExpense:edit']"
						v-else-if="checkApprovalPermission(roles) && (scope.row.status !== 0  && scope.row.status !== 9)">
						审批
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)"
						v-if="scope.row.status == 9">
						查看
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-edit" :key="scope.row.id"
						v-if="scope.row.status == 0  &&activeName == 5" disabled>
						等待提交
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-view" :key="scope.row.id"
						v-if="(scope.row.status == 1 || scope.row.status == 2) && activeName == '0'"
						@click="handleWithdraw(scope.row)">
						撤回审批
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
						v-hasPermi="['business:bxExpense:remove']" v-if="scope.row.status == 0  && activeName == 0">
						删除
					</el-button>
					<el-button size="mini" type="text" icon="el-icon-printer" @click="handlePrint(scope.row)"
						v-if="scope.row.status == 9">
						打印
					</el-button>
				</template>

			</el-table-column>
		</el-table>

		<!-- 分页组件 -->
		<pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<bxForm ref="bxForm" :title="title" v-if="formVisble" @close="handleClose"></bxForm>

		<el-dialog title="单据打印预览" custom-class="printPreview" :visible.sync="printShow" width="297mm" append-to-body>
			<bxTemplate :rowData="rowData"></bxTemplate>
		</el-dialog>
	</div>
</template>

<script>
	import {
		listBxExpense,
		getBxExpense,
		delBxExpense,
		addBxExpense,
		updateBxExpense
	} from "@/api/business/bxExpense";

	import {
		listUser
	} from "@/api/system/user"

	import {
		deptTreeSelect
	} from "@/api/system/user";

	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";

	import bxForm from "./bxForm.vue";

	import bxTemplate from "../bxTemplate/index.vue"

	export default {
		components: {
			Treeselect,
			bxForm,
			bxTemplate
		},
		data() {
			return {
				// 当前激活的选项卡
				activeName: "0",
				// 是否显示加载遮罩层
				loading: true,
				// 选中的数组
				ids: [],
				// 非单个禁用
				single: true,
				// 非多个禁用
				multiple: true,
				// 是否显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 报销管理表格数据
				bxExpenseList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 用户数据
				userData: [],
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					// 默认Type为"1"常规报销
					type: 1,
					uid: null,
					status: null,
					statuses: null,
					deptId: null,
					startTime: null,
					endTime: null,
				},
				// 用户角色
				roles: [],
				// 查询条件时间
				timeData: [],
				// 新增修改弹窗
				formVisble: false,
				// 打印预览弹窗
				printShow: false,
				// 要打印的数据
				rowData: [],
			};
		},
		watch: {
			$route: {
				handler: function(val, oldVal) {
					if (val.query.formParam == undefined) {
						this.formVisble = false;
					} else if (val.query.formParam == 'dHJ1ZQ==') {
						this.handleAdd();
					}
				},
				deep: true,
				immediate: true
			}
		},
		created() {
			this.getUserData();
			this.getDeptTree();
			// 从vuex(状态)中获取当前用户有哪些角色
			this.roles = this.$store.getters.roles;
			// 如果选项卡为"我的数据--0"时赋值查询UID(本人)
			if (this.activeName == 0) {
				this.queryParams.uid = this.$store.state.user.userId;
			};
			this.getList();
		},
		computed: {
			// 根据角色动态生成允许显示的选项卡
			allowedTabs() {
				const tabs = [{
						label: '我的数据',
						name: '0'
					},
					{
						label: '全部数据',
						name: '5',
						roles: ['admin', 'BOSS', 'DEPT_LEADER']
					},
					{
						label: '部门审核',
						name: '1',
						roles: ['DEPT_LEADER']
					},
					{
						label: '领导审核',
						name: '2',
						roles: ['BOSS']
					},
				];
				return tabs.filter(tab => !tab.roles || this.hasRole(tab.roles));
			},
		},
		methods: {
			/** 查询报销管理列表 */
			getList() {
				this.loading = true;
				listBxExpense(this.queryParams).then(response => {
					this.bxExpenseList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			// 获取用户列表
			getUserData() {
				listUser().then(res => {
					this.userData = res.rows;
				})
			},
			/** 查询部门下拉树结构 */
			getDeptTree() {
				deptTreeSelect().then(response => {
					this.deptOptions = response.data;
				});
			},
			// 查询条件时间选择
			timeChange(val) {
				this.queryParams.startTime = val[0] + " 00:00:00";
				this.queryParams.endTime = val[1] + " 23:59:59";
			},
			// 处理标签页点击事件
			handleClick(data) {
				this.activeName = data.name;
				if (data.name == 0) {
					this.queryParams.uid = this.$store.state.user.userId;
					this.queryParams.status = null;
					this.queryParams.statuses = null
				} else if (data.name == 5) {
					this.queryParams.uid = null;
					this.queryParams.status = null;
					this.queryParams.statuses = null;
				} else {
					this.queryParams.uid = null;
					this.queryParams.status = null;
					if (this.hasRole(['admin', 'BOSS'])) {
						this.queryParams.statuses = '1,2';
					} else if (this.hasRole(['DEPT_LEADER'])) {
						this.queryParams.statuses = '1';
					}
				}
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 10;
				this.getList();
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.timeData = [];
				this.queryParams.startTime = null;
				this.queryParams.endTime = null;
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			// 新增报销单据
			handleAdd() {
				this.formVisble = true;
				this.title = "新增报销";
				setTimeout(() => {
					this.$refs.bxForm.initPage({
						isAdd: 'add',
						type: 1
					})
				}, 50)
			},
			// 编辑/审批
			handleEdit(row) {
				const id = row.id || this.ids
				getBxExpense(id).then(res => {
					this.formVisble = true;
					this.title = "修改报销管理";
					setTimeout(() => {
						this.$refs.bxForm.initPage(res.data)
					}, 50)
				});
			},
			// 查看报销单据
			handleView(row) {
				const id = row.id || this.ids
				getBxExpense(id).then(res => {
					this.formVisble = true;
					this.title = "修改报销管理";
					setTimeout(() => {
						this.$refs.bxForm.initPage(res.data)
					}, 50)
				});
			},
			/**关闭页面 */
			handleClose() {
				this.formVisble = false;
				this.getList();
			},
			// 检查是否具有审批权限
			checkApprovalPermission(roles) {
				let isAllow = true;
				if (this.activeName == 0) {
					isAllow = false;
				} else {
					const requiredRoles = ['admin', 'BOSS', 'DEPT_LEADER'];
					isAllow = requiredRoles.some(role => roles.indexOf(role) !== -1)
				}
				return isAllow;
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const ids = row.id || this.ids;
				this.$modal.confirm('是否确认删除报销管理编号为"' + ids + '"的数据项？').then(function() {
					return delBxExpense(ids);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			handleWithdraw(row) {
				row.status = 0;
				updateBxExpense(row).then(response => {
					this.$modal.msgSuccess("撤回成功");
					this.getList();
				})
			},
			handlePrint(row) {
				getBxExpense(row.id).then(res => {
					this.printShow = true;
					this.rowData = res.data;
				})
			}
		},
	};
</script>

<style>
	/* 可以添加样式 */
</style>
